package com.Leetcode;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * project : my-learn
 *
 * LeetCode 977：有序数组的平方
 *
 * 一个按非递减顺序排序的整数数组 nums，返回每个数字的平方组成的新数组，要求也按非递减顺序排序。
 *
 * 示例
 *
 * 输入：nums = [-4,-1,0,3,10]
 *
 * 输出：[0,1,9,16,100]
 *
 * 解释：平方后，数组变为 [16,1,0,9,100]，排序后，数组变为 [0,1,9,16,100]
 *
 * 提示
 *
 * 1 <= len(nums) <= 10^4
 * -10^4 <= nums[i] <= 10^4
 * nums 已按非递减顺序排序
 *
 * @author yisl
 * @date 2022-07-14【星期四】
 **/
public class Leetcode977 {
    //位图解法
    public static int sortedSquares(int[] arr){
        int i=0;
        int j=arr.length-1;
        int res = 1;
        int temp = Math.abs(arr[i]);
        while(i<=j){
            if(Math.abs(arr[i])>Math.abs(arr[j])){
                if(temp!=Math.abs(arr[i])){
                    res++;
                    temp = Math.abs(arr[i]);
                }
                i++;
            }else{
                if(temp!=Math.abs(arr[j])){
                    res++;
                    temp = Math.abs(arr[j]);
                }
                j--;
            }
        }
        return res;
    }


    public static void main(String[] args) throws ClassNotFoundException {
        int[] a = {-6,-1,0,0,1,1,2,5};
        System.out.println(sortedSquares(a));



    }



    public static void readFile(String filePath)  {
        File file = new File(filePath);
        String result;
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            while((result = reader.readLine())!=null) {
                System.out.println(result);
            }
        } catch (IOException e) {
            System.out.println("readFile method catch block.");
            //MyException ex = new MyException("read file failed.");
            //ex.initCause(e);
            //throw ex;
        } finally {
            System.out.println("readFile method finally block.");
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

